package dongbai.soft.filter;


import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.netflix.zuul.http.HttpServletRequestWrapper;
import com.netflix.zuul.http.ServletInputStreamWrapper;
import dongbai.soft.service.UserService;
import dongbai.soft.utils.R;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.nio.charset.Charset;


@Component
public class LoginCheckFilter extends ZuulFilter {
    @Autowired
    private UserService userService;

    //filter的类型
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    //filter执行的顺序，越小越先执行
    @Override
    public int filterOrder() {
        return 1;
    }

    //需要进入filter的路径选择
    @Override
    public boolean shouldFilter() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();//获取访问的路径
        String requestURI = request.getRequestURI();
        return !requestURI.endsWith("/login") && !requestURI.endsWith("/register") && !requestURI.endsWith("/manual");
    }

    //执行过滤操作
    @SneakyThrows
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();//获取访问的路径
        HttpServletResponse response = ctx.getResponse();
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token) || userService.getids(token) == null) {
            response.setContentType("application/json;charset=utf-8");
            R r = R.error("身份验证失败，请先登录");
            response.getWriter().write(r.toString());
            //3.2.阻止filter继续往后执行
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        } else {
            // 编码格式
            String charset = ctx.getRequest().getCharacterEncoding();
            InputStream in = (InputStream) ctx.get("requestEntity");
            if (null == in) {
                in = ctx.getRequest().getInputStream();
            }

            String requestEntityStr = StreamUtils.copyToString(in, Charset.forName(charset));
            requestEntityStr = URLDecoder.decode(requestEntityStr, charset);
            JSONObject requestEntityJson = JSONObject.parseObject(requestEntityStr);
            if (requestEntityJson == null) {
                requestEntityJson = new JSONObject();
            }
            // 新增参数
            requestEntityJson.put("UID", userService.getids(token));
            byte[] requestEntityBytes = requestEntityJson.toJSONString().getBytes(charset);
            ctx.setRequest(new HttpServletRequestWrapper(ctx.getRequest()) {
                @Override
                public ServletInputStream getInputStream() throws IOException {
                    return new ServletInputStreamWrapper(requestEntityBytes);
                }

                @Override
                public int getContentLength() {
                    return requestEntityBytes.length;
                }

                @Override
                public long getContentLengthLong() {
                    return requestEntityBytes.length;
                }
            });

        }
        return null;
    }
}
